import { ActionTree, Module, MutationTree } from 'vuex';
import { find } from 'lodash';
import { ITodoState, RootState } from '@/typings/store';
import mutationType from '../mutation-type';
import { ITodoItem } from '@/typings/todo';

export const state: ITodoState = {
  list: [
    {
      id: '0',
      text: '吃饭',
      status: 'Wait',
    },
    {
      id: '1',
      text: '喝水',
      status: 'Finish',
    },
  ],
};

export const mutations: MutationTree<any> = {
  [mutationType.ADD_TODO]: (state: ITodoState, item: ITodoItem): void => {
    state.list.push(item);
  },
  [mutationType.CHANGE_TODO_STATUS]: (state: ITodoState, id: string): void => {
    const target = find(state.list, (o) => o.id === id) as ITodoItem;
    if (!target) {
      return;
    }
    target.status = 'Finish';
  },
};

export const actions: ActionTree<any, any> = {
  async [mutationType.ADD_TODO]({ commit }, item: ITodoItem) {
    commit(mutationType.ADD_TODO, item);
  },
};

const todo: Module<ITodoState, RootState> = {
  namespaced: true,
  state,
  mutations,
  actions,
};
export default todo;
